<template>
  <div class="vr-container">
    <!-- Photo Sphere Viewer 容器 -->
    <div id="viewer-container"></div>

    <!-- 控制按钮 -->
    <div class="controls">
      <button @click="prevImage">上一张</button>
      <button @click="nextImage">下一张</button>
    </div>
  </div>
</template>

<script lang="ts">
// 导入所需的库
// 使用类型导入方式导入Vue
import type { Ref, ShallowRef } from 'vue';
import { ref, onMounted, onUnmounted, shallowRef } from 'vue';

// 导入@photo-sphere-viewer/core
import { Viewer } from '@photo-sphere-viewer/core';
import '../../../../node_modules/@photo-sphere-viewer/core/index.css';

// 定义图片数组
const images = [
  // 使用本地VR图片
  '/src/assets/images/bg.png',
  '/src/assets/images/sphere.jpg'
];

// 当前显示的图片索引
const currentImageIndex = ref(0);
// 全景查看器实例
const viewer = shallowRef(null);

// 切换到下一张图片
const nextImage = () => {
  currentImageIndex.value = (currentImageIndex.value + 1) % images.length;
  updateViewer();
};

// 切换到上一张图片
const prevImage = () => {
  currentImageIndex.value = (currentImageIndex.value - 1 + images.length) % images.length;
  updateViewer();
};

// 更新查看器显示的图片
const updateViewer = async () => {
  if (viewer.value) {
    try {
      // 检查新图片是否可访问
      await checkImagePath(images[currentImageIndex.value]);
      viewer.value.setPanorama(images[currentImageIndex.value]);
      console.log('全景图片更新成功');
    } catch (error) {
      handleViewerError(error);
    }
  }
};

// 初始化全景查看器
const initViewer = async () => {
  try {
    // 销毁之前的实例（如果存在）
    if (viewer.value) {
      viewer.value.destroy();
    }

    // 检查容器是否存在
    const container = document.getElementById('viewer-container');
    if (!container) {
      throw new Error('查看器容器不存在');
    }

    // 检查当前图片是否可访问
    await checkImagePath(images[currentImageIndex.value]);

    // 创建新的查看器实例
    viewer.value = new Viewer({
      container: container,
      panorama: images[currentImageIndex.value],
      defaultZoomLvl: 100,
      navbar: ['zoom', 'fullscreen', 'caption'],
      caption: '360° 全景图片',
      // 移动端优化配置
      touchmoveTwoFingers: true,
      mousewheelCtrlKey: false,
      keyboard: false, // 移动端禁用键盘
      mousewheel: true,
      moveInertia: true,
      // 响应式配置
      autorotateIdleDelay: 0,
      autorotateSpeed: '2rpm',
      // 触摸手势
      touchmove: true,
      pinchToZoom: true
    });

    // 添加查看器错误事件监听
    viewer.value.on('error', handleViewerError);

    console.log('全景查看器初始化成功');
  } catch (error) {
    handleViewerError(error);
  }
};

// 组件挂载时初始化查看器
onMounted(() => {
  console.log('组件已挂载，准备初始化全景查看器');
  // 确保DOM完全加载
  setTimeout(() => {
    console.log('尝试初始化全景查看器...');
    initViewer();
  }, 100);
});

// 添加错误处理的辅助函数
const handleViewerError = (error) => {
  console.error('Photo Sphere Viewer 错误:', error);
  alert('全景图加载失败: ' + error.message);
};

// 检查图片路径是否可访问
const checkImagePath = (path) => {
  console.log('检查图片路径:', path);
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      console.log('图片加载成功:', path);
      resolve(true);
    };
    img.onerror = () => {
      console.error('图片加载失败:', path);
      reject(new Error(`无法加载图片: ${path}`));
    };
    img.src = path;
  });
};

// 组件卸载时销毁查看器
onUnmounted(() => {
  if (viewer.value) {
    viewer.value.destroy();
  }
});

// 默认导出组件
export default {
  name: 'ImportTable'
};
</script>

<style scoped>
/* 重置浏览器默认样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

.vr-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

#viewer-container {
  width: 100%;
  height: 100%;
}

.controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
  display: flex;
  gap: 10px;
  /* 移动端优化 */
  padding: 0 20px;
  max-width: 100%;
  box-sizing: border-box;
}

button {
  padding: 12px 24px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  /* 移动端优化 */
  min-height: 44px;
  min-width: 80px;
  -webkit-tap-highlight-color: transparent;
  user-select: none;
  -webkit-user-select: none;
  transition: all 0.3s ease;
}

button:hover,
button:active {
  background-color: rgba(0, 0, 0, 0.7);
  transform: scale(0.95);
}

/* 响应式布局 - 移动端适配 */
@media (max-width: 768px) {
  .controls {
    bottom: 15px;
    gap: 8px;
    padding: 0 15px;
  }

  button {
    padding: 10px 20px;
    font-size: 14px;
    min-height: 40px;
    min-width: 70px;
  }
}

@media (max-width: 480px) {
  .controls {
    bottom: 10px;
    gap: 6px;
    flex-direction: column;
    align-items: center;
  }

  button {
    padding: 8px 16px;
    font-size: 12px;
    min-height: 36px;
    min-width: 60px;
    margin: 2px 0;
  }
}
</style>
